<template>
  <!-- 内容区域 -->
  <el-main>
    <div>
      <el-tabs
        class="tabHight"
        :tab-position="tabPosition"
        v-model="siteTabs"
        @tab-click="invalidateMap"
      >
        <el-tab-pane label="详情" name="first">
          <!-- from表单 -->
          <el-form
            class="tabHight_auto"
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="auto"
            size="mini"
          >
            <el-form-item label="Token:" prop="token">
              <el-input
                v-model="ruleForm.token"
                placeholder="请输入2-30字符标识符"
              ></el-input>
            </el-form-item>
            <el-form-item label="名称" prop="sitename">
              <el-input
                v-model="ruleForm.sitename"
                placeholder="请输入15字符以内名称"
              ></el-input>
            </el-form-item>
            <!-- 站点类型 -->
            <el-form-item label="站点类型:" prop="sitetoken">
              <el-select
                class="w100"
                v-model="ruleForm.sitetoken"
                placeholder="请选择站点类型"
              >
                <el-option
                  v-for="item in areaTypeList"
                  :key="item.token"
                  :label="item.name"
                  :value="item.token"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="图像:" prop="imageUrl">
              <div style="width: 100%">
                <el-row>
                  <el-col :span="6">
                    <app-upload
                      tips=""
                      :is-resolution="true"
                      :width="720"
                      :height="294"
                      @subUploadSucceed="handleUploadSucceed"
                    />
                  </el-col>
                  <el-col :span="18">
                    <div class="imageHome" v-if="showImg">
                      <img
                        v-if="ruleForm.imageUrl"
                        :src="ruleForm.imageUrl | filtersFileUrl()"
                        class="image-size"
                      />
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input
                type="textarea"
                v-model="ruleForm.description"
                placeholder="请输入描述"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <!-- 边界样式 -->
        <el-tab-pane label="边界" name="second">
          <div id="mapAddInternalSite"></div>
        </el-tab-pane>
        <!-- 元数据样式 -->
        <el-tab-pane label="元数据" name="third">
          <metaData
            :editmetaData="editmetaData"
            :isedit="isedit"
            @sendmetaDatas="sendmetaData"
          />
        </el-tab-pane>
      </el-tabs>
      <el-divider style="color: #000000"></el-divider>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible" size="mini">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
          size="mini"
          :loading="btnLoading"
          >确 定</el-button
        >
      </div>
    </div>
  </el-main>
</template>

<script>
import CoverDatatab from "../opensite/coverDatatab.vue";
import MetaData from "../opensite/metaData.vue";
import AppUpload from "../device/devicegroups/UploadImage.vue";
import "../../styles/uploadImg.sass";
import {
  initMap,
  addControlOptions,
  createIcon,
} from "../../utils/leaflet-map";
import { addAreas, getAreatypes } from "@/api/superlinkAreat";
import { TOKEN_RULES } from "@/utils/local";
export default {
  components: {
    CoverDatatab,
    MetaData,
    AppUpload,
  },
  data() {
    return {
      btnLoading: false,
      tabPosition: "left",
      map: "",
      layer: [],
      isedit: false, //true为编辑页进入，false为添加页进入
      siteTabs: "first",
      value: "",
      ruleForm: {
        token: "",
        sitename: "",
        imageUrl: "",
        description: "",
        sitetoken: "",
        bounds: {},
      },
      areaTypeList: [],
      typename: "",
      coverData: [],
      metaData: {},
      editcoverData: [],
      editmetaData: [],
      formInline: { date: "", name: "" },
      rules: {
        token: TOKEN_RULES,
        sitename: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 2, max: 15, message: "输入格式不正确", trigger: "blur" },
        ],
        imageUrl: [{ required: true, message: "请上传图片", trigger: "blur" }],
        sitetoken: [
          {
            required: true,
            message: "请选择站点类型",
            trigger: ["blur", "change"],
          },
        ],
      },
      // coverDataSelectedIds: [],
      metaDataJson: {},
      createArea: {},
      typetokn: "",
      areaToken: this.$route.query.areaToken,
      mapBounds: [],
    };
  },
  mounted() {
    this.AreaTypes();
    this.load_Map_2();
  },
  computed: {
    showImg: function () {
      return this.ruleForm.imageUrl != "";
    },
  },
  methods: {
    // 图片上传
    handleUploadSucceed(url) {
      this.ruleForm.imageUrl = url;
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    // 请求站点类型列表
    AreaTypes() {
      var that = this;
      var param = { includeContainedAreaTypes: false, page: 1, pageSize: 100 };
      getAreatypes(param).then((res) => {
        that.areaTypeList = res.data.results;
      });
    },
    // 点击下拉
    selectAreaTypes(val) {
      console.log(val); // 此时打印的直接就是id
    },

    dialogFormVisible() {
      this.$emit("closaddsite", false);
      this.ruleForm = {
        token: "",
        sitename: "",
        imageUrl: "",
        description: "",
        sitetoken: "",
      };
      this.map.remove(),
        (this.layer = []),
        (this.formInline = { date: "", name: "" });
      this.metaData = [];
    },

    // 初始化地图
    load_Map_2() {
      var that = this;
      var latlng = that.ruleForm.bounds;
      var map = initMap("mapAddInternalSite", latlng, 5);
      addControlOptions(map, [
        "drawRectangle",
        "drawPolygon",
        "removalMode",
        "enable",
        "editMode",
      ]);

      map.on("pm:create", (e) => {
        if (that.layer) {
          map.removeLayer(that.layer); // 移除已有图层,限制只有一个marker
        }
        // 清空参数，只保留当前
        that.mapBounds = [];
        // 转换数据格式
        that.layer = e.layer;
        let maplist = e.layer._latlngs;
        let ele = {};
        maplist[0].forEach((item) => {
          ele = {
            latitude: item.lat,
            longitude: item.lng,
          };
          that.mapBounds.push(ele);
        });
        // console.log(e);
      });
      map.on("pm:remove", (e) => {
        that.layer = [];
      });
      that.map = map;
    },

    // 表单提交
    submitForm(formName) {
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formData = {};
          formData.areaTypeToken = this.ruleForm.sitetoken;
          formData.name = this.ruleForm.sitename;
          formData.metadata = this.metaDataJson;
          formData.imageUrl = this.ruleForm.imageUrl;
          formData.description = this.ruleForm.description;
          formData.token = this.ruleForm.token;
          formData.backgroundColor = "";
          formData.borderColor = "";
          formData.bounds = that.mapBounds;
          formData.foregroundColor = "";
          formData.icon = "";
          formData.parentToken = this.areaToken;
          this.btnLoading = true;
          addAreas(formData)
            .then((res) => {
              console.log("res :>> ", res.data);
              that.createArea = res.data;
              console.log("that.createArea", that.createArea);
              this.$msg({
                type: "success",
                message: "操作成功!",
              });
              this.dialogFormVisible();
              this.$emit("AddsubmitForm", false);
            })
            .finally((f) => {
              this.btnLoading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //含盖页回传
    sendids(ids) {
      this.coverDataSelectedIds = ids;
    },

    //元数据页回传
    sendmetaData(md) {
      this.metaDataJson = md;
    },

    //地图重新调整位置
    invalidateMap(tab) {
      if (tab.name == "second") {
        this.$nextTick(() => {
          this.map.invalidateSize(true);
        });
      }
    },
  },
};
</script>

<style scoped>
.dialog-footer {
  float: right;
  /* margin-top: 25px; */
}
.demo-form-inline {
  margin-top: 10px;
}
.avatar {
  text-align: center;
  margin-top: 12px;
}
.name {
  margin-top: 13px;
  text-align: center;
  font-weight: 700;
  font-size: 18px;
}
.text {
  font-size: 14px;
  margin-top: 11px;
  text-align: center;
  /* width: 100px; */
}
.element-icons {
  font-size: 20px;
  font-weight: 600;
  float: left;
  margin-top: -91px;
  margin-left: 91%;
}
.el-pagination {
  margin-left: 32%;
  margin-top: 30px;
}

.list-content {
  margin-top: -25px;
}
.span-box {
  display: inline-block;
  position: relative;
}
.ico-pre {
  position: absolute;
  left: -21px;
  top: 12px;
}
#mapAddInternalSite {
  width: 100%;
  height: calc(50vh);
  z-index: 1;
}
</style>>
